import React, { useState, useEffect, useMemo, useCallback } from "react";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import {
  Search,
  Plus,
  Upload,
  MoreHorizontal,
  ChevronLeft,
  ChevronRight,
  AlertTriangle,
  Edit,
  Trash2,
} from "lucide-react";
import { Badge } from "@/components/ui/badge";
import SafetyRiskPointForm from "../SafetyRiskPointForm";
import SafetyRiskPointImportModal from "../SafetyRiskPointImportModal";

// 空函数默认值
const noop = () => {};

// 1. 风险种类数据源（常量，无需useMemo）
const riskTypeS = [
  { key: "poisoning", label: "中毒", description: "" },
  { key: "suffocation", label: "窒息", description: "" },
  { key: "tripFall", label: "摔绊", description: "" },
  { key: "fall", label: "坠落", description: "" },
  { key: "fallFromHeight", label: "高处坠落", description: "" },
  { key: "struckByObject", label: "物体打击", description: "" },
  { key: "strike", label: "打击", description: "" },
  { key: "sprain", label: "扭伤", description: "" },
  { key: "burn", label: "烧伤", description: "" },
  { key: "burnFire", label: "烧伤（引起火灾）", description: "" },
  { key: "scald", label: "灼伤", description: "" },
  { key: "scaldBurn", label: "灼（烫）伤", description: "" },
  { key: "electricShock", label: "触电", description: "" },
  { key: "personalElectricShock", label: "人身触电", description: "" },
  { key: "equipmentTrip", label: "设备跳闸", description: "" },
  { key: "equipmentDamage", label: "设备损坏", description: "" },
  { key: "equipmentBreakdown", label: "设备破损", description: "" },
  { key: "equipmentShutdown", label: "设备停运", description: "" },
  { key: "equipmentPowerOutage", label: "停电", description: "" },
  { key: "equipmentBurn", label: "设备烧损", description: "" },
  { key: "partialPowerOutage", label: "局部停电", description: "" },
  { key: "fire", label: "火灾", description: "" },
  { key: "explosion", label: "爆炸", description: "" },
  { key: "collapse", label: "坍塌", description: "" },
  { key: "landslide", label: "塌方", description: "" },
  { key: "drowning", label: "溺水", description: "" },
  { key: "drowningAlt", label: "淹溺", description: "" },
  { key: "stab", label: "刺伤", description: "" },
  { key: "cut", label: "割伤", description: "" },
  { key: "clip", label: "夹伤", description: "" },
  { key: "entanglement", label: "绞伤", description: "" },
  { key: "mechanicalInjury", label: "机械伤害", description: "" },
  { key: "lungDysfunction", label: "肺功能障碍", description: "" },
  { key: "occupationalDisease", label: "职业病", description: "" },
  { key: "crash", label: "碰撞", description: "" },
  { key: "crushInjury", label: "压伤", description: "" },
  { key: "socialResponsibility", label: "社会责任", description: "" },
  { key: "personalCasualty", label: "人身伤亡", description: "" },
  { key: "frameOverturn", label: "架体倾覆", description: "" },
  { key: "trafficAccident", label: "交通意外", description: "" },
];

export default function SafetyRisks({
  riskPoints = [],
  onSave = noop,
  onDelete = noop,
  onFilteredCountChange = noop,
  onRefreshData = noop,
  isLoading = false,
}) {
  // 2. 动态生成风险种类映射（移到组件内部）
  const riskTypeMap = useMemo(() => {
    return riskTypeS.reduce((map, type) => {
      map[type.key] = type.label;
      return map;
    }, {});
  }, []);

  // 状态管理：表单、筛选、分页、导入模态框
  const [showForm, setShowForm] = useState(false);
  const [editingRisk, setEditingRisk] = useState(null);
  const [searchTerm, setSearchTerm] = useState("");
  const [filterCategory, setFilterCategory] = useState("all");
  const [showImportModal, setShowImportModal] = useState(false);
  const [currentPage, setCurrentPage] = useState(1);
  const [itemsPerPage, setItemsPerPage] = useState(10);
  const [filteredRisks, setFilteredRisks] = useState([]);

  // 提取唯一一级分类（移到组件内部）
  const uniquePrimaryCategories = useMemo(() => {
    const uniqueCats = [...new Set(riskPoints.map((r) => r.primaryCategory).filter(Boolean))];
    return uniqueCats.sort((a, b) => a.localeCompare(b));
  }, [riskPoints]);

  // 筛选逻辑：支持搜索（编码/名称/描述）+ 一级分类筛选
  useEffect(() => {
    let result = [...riskPoints];
    // 1. 搜索匹配：风险编码、风险名称、风险描述
    if (searchTerm) {
      const lowerTerm = searchTerm.toLowerCase();
      result = result.filter(
        (risk) =>
          risk.riskCode?.toLowerCase().includes(lowerTerm) ||
          risk.riskName?.toLowerCase().includes(lowerTerm) ||
          risk.riskDescription?.toLowerCase().includes(lowerTerm)
      );
    }
    // 2. 一级分类筛选
    if (filterCategory !== "all") {
      result = result.filter((risk) => risk.primaryCategory === filterCategory);
    }
    setFilteredRisks(result);
    // 通知筛选后数量
    onFilteredCountChange(result.length);
    // 筛选后重置页码
    setCurrentPage(1);
  }, [riskPoints, searchTerm, filterCategory, onFilteredCountChange]);

  // 分页处理函数
  const handlePageChange = (pageNum) => {
    if (pageNum >= 1 && pageNum <= totalPages) {
      setCurrentPage(pageNum);
      // 分页切换时滚动到表格顶部
      window.scrollTo({ top: 0, behavior: "smooth" });
    }
  };

  const handleItemsPerPageChange = (count) => {
    setItemsPerPage(count);
    setCurrentPage(1); // 切换每页条数重置页码
  };

  // 分页数据计算
  const totalItems = filteredRisks.length;
  const totalPages = Math.ceil(totalItems / itemsPerPage);
  const indexOfLastItem = currentPage * itemsPerPage;
  const indexOfFirstItem = indexOfLastItem - itemsPerPage;
  const currentItems = filteredRisks.slice(indexOfFirstItem, indexOfLastItem);

  // 渲染分页组件
  const renderPagination = () => (
    <div className="flex flex-col sm:flex-row items-center justify-between gap-4 px-4 py-3 border-t">
      <div className="text-sm text-gray-500">
        共 {totalItems} 条数据，显示
        {(currentPage - 1) * itemsPerPage + 1} 到
        {Math.min(currentPage * itemsPerPage, totalItems)} 条
      </div>
      <div className="flex items-center gap-2">
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <Button variant="outline" size="sm" className="h-8">
              每页 {itemsPerPage} 条
              <MoreHorizontal className="ml-2 h-4 w-4" />
            </Button>
          </DropdownMenuTrigger>
          <DropdownMenuContent align="end">
            {[5, 10, 20, 50].map((count) => (
              <DropdownMenuItem
                key={count}
                onClick={() => handleItemsPerPageChange(count)}
              >
                {count} 条/页
              </DropdownMenuItem>
            ))}
          </DropdownMenuContent>
        </DropdownMenu>
        <div className="flex items-center gap-1">
          <Button
            variant="outline"
            size="icon"
            className="h-8 w-8"
            onClick={() => handlePageChange(currentPage - 1)}
            disabled={currentPage === 1}
          >
            <ChevronLeft className="h-4 w-4" />
            <span className="sr-only">上一页</span>
          </Button>
          {Array.from({ length: Math.min(5, totalPages) }, (_, i) => {
            let pageNum;
            if (totalPages <= 5) {
              pageNum = i + 1;
            } else if (currentPage <= 3) {
              pageNum = i + 1;
            } else if (currentPage >= totalPages - 2) {
              pageNum = totalPages - 4 + i;
            } else {
              pageNum = currentPage - 2 + i;
            }
            return (
              <Button
                key={pageNum}
                variant={currentPage === pageNum ? "default" : "outline"}
                size="icon"
                className="h-8 w-8"
                onClick={() => handlePageChange(pageNum)}
              >
                {pageNum}
              </Button>
            );
          })}
          <Button
            variant="outline"
            size="icon"
            className="h-8 w-8"
            onClick={() => handlePageChange(currentPage + 1)}
            disabled={currentPage === totalPages}
          >
            <ChevronRight className="h-4 w-4" />
            <span className="sr-only">下一页</span>
          </Button>
        </div>
      </div>
    </div>
  );

  // 编辑操作：打开表单并滚动到表单位置
  const handleEdit = (risk) => {
    setEditingRisk(risk);
    setShowForm(true);
    setTimeout(() => {
      const formElement = document.getElementById("emergency-measure-form");
      if (formElement) {
        formElement.scrollIntoView({ behavior: "smooth", block: "start" });
      }
    }, 250);
  };

  // 取消表单
  const handleCancel = () => {
    setShowForm(false);
    setEditingRisk(null);
  };

  // 提交表单
  const handleSubmit = async (data) => {
    await onSave(editingRisk ? { ...data, id: editingRisk.id } : data);
    handleCancel();
  };

  // 风险等级样式
  const getRiskLevelStyle = (riskLevelName) => {
    const levelConfig = {
      "重大风险": { color: "#dc2626", bgColor: "bg-red-100 text-red-700" },
      "较大风险": { color: "#ea580c", bgColor: "bg-orange-100 text-orange-700" },
      "一般风险": { color: "#d97706", bgColor: "bg-yellow-100 text-yellow-700" },
      "低风险": { color: "#2563eb", bgColor: "bg-blue-100 text-blue-700" },
      "可接受风险": { color: "#16a34a", bgColor: "bg-green-100 text-green-700" },
      "V级(可接受风险)": { color: "#16a34a", bgColor: "bg-green-100 text-green-700" },
    };
    return levelConfig[riskLevelName] || { color: "#6b7280", bgColor: "bg-gray-100 text-gray-700" };
  };

  // 格式化风险种类
  const formatRiskTypes = useCallback((riskTypes) => {
    if (!Array.isArray(riskTypes) || riskTypes.length === 0) {
      return <span className="text-gray-400 text-xs">无</span>;
    }

    const validRiskTypes = riskTypes.filter(
      (typeKey) => typeKey && riskTypeMap[typeKey]
    );

    if (validRiskTypes.length === 0) {
      return <span className="text-gray-400 text-xs">无有效风险种类</span>;
    }

    return (
      <div className="flex flex-wrap gap-1 max-w-[220px]">
        {validRiskTypes.map((typeKey) => (
          <Badge
            key={typeKey}
            variant="secondary"
            className="text-xs bg-gray-100 text-gray-700 hover:bg-gray-200"
            title={riskTypeMap[typeKey]}
          >
            {riskTypeMap[typeKey]}
          </Badge>
        ))}
      </div>
    );
  }, [riskTypeMap]);

  // 格式化控制措施
  const formatControlMeasures = (measures = []) => {
    const validMeasures = measures.filter(m => m.trim());
    if (validMeasures.length === 0) return <span className="text-gray-400 text-xs">无</span>;
    if (validMeasures.length === 1) {
      return (
        <span className="text-xs" title={validMeasures[0]}>
          {validMeasures[0].length > 15 ? `${validMeasures[0].slice(0, 15)}...` : validMeasures[0]}
        </span>
      );
    }
    return (
      <span className="text-xs" title={validMeasures.join("；")}>
        {validMeasures.length} 条措施
      </span>
    );
  };

  // 格式化分类
  const formatCategory = (category) => category || <span className="text-gray-400 text-xs">未设置</span>;

  // 格式化适用范围
  const formatApplicableScope = (scope) => {
    if (!scope) return <span className="text-gray-400 text-xs">无</span>;
    return (
      <span className="text-xs" title={scope}>
        {scope.length > 15 ? `${scope.slice(0, 15)}...` : scope}
      </span>
    );
  };

  return (
    <div className="space-y-6">
      {/* 搜索+筛选+操作栏 */}
      <div className="flex flex-col md:flex-row gap-3 items-start md:items-center">
        <div className="relative flex-1 w-full">
          <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4" />
          <Input
            placeholder="搜索风险编码、名称或描述..."
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            className="pl-10 h-10 border-gray-200 focus:border-blue-400 focus:ring-1 focus:ring-blue-400 transition-all"
            suffix={
              searchTerm && (
                <button
                  onClick={() => setSearchTerm("")}
                  className="text-gray-400 hover:text-gray-600"
                >
                  ×
                </button>
              )
            }
          />
        </div>

        {/* 一级分类筛选 */}
        <Select value={filterCategory} onValueChange={setFilterCategory}>
          <SelectTrigger className="w-full md:w-[200px] h-10 border-gray-200">
            <SelectValue placeholder="所有一级分类" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all">所有一级分类</SelectItem>
            {uniquePrimaryCategories.map((cat) => (
              <SelectItem key={cat} value={cat}>
                {cat}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>

        {/* 批量导入按钮 */}
        <Button
          variant="outline"
          className="h-10 px-4 transition-all"
          onClick={() => setShowImportModal(true)}
        >
          <Upload className="w-4 h-4 mr-2" />
          批量导入
        </Button>

        {/* 新建按钮 */}
        <Button
          className="text-white bg-purple-600 hover:bg-purple-700 h-10 px-4 transition-all shadow-sm hover:shadow"
          onClick={() => {
            setEditingRisk(null);
            setShowForm(true);
          }}
        >
          <Plus className="w-4 h-4 mr-2" />
          新建危险点
        </Button>
      </div>

      {/* 批量导入模态框 */}
      {showImportModal && (
        <SafetyRiskPointImportModal
          isOpen={showImportModal}
          onClose={() => setShowImportModal(false)}
          onImportSuccess={() => {
            setShowImportModal(false);
            onRefreshData();
          }}
        />
      )}

      {/* 编辑/新建表单 */}
      {showForm && (
        <SafetyRiskPointForm
          id="emergency-measure-form"
          riskPoint={editingRisk}
          onSubmit={handleSubmit}
          onCancel={handleCancel}
        />
      )}

      {/* 表格+分页区域 */}
      {isLoading ? (
        <div className="text-center py-16 px-4 text-gray-500 border rounded-lg bg-gray-50 border-gray-200">
          加载中...
        </div>
      ) : totalItems > 0 ? (
        <div className="rounded-lg border border-gray-200 overflow-hidden shadow-sm">
          <div className="overflow-x-auto">
            <Table>
              <TableHeader className="bg-gray-50 border-b border-gray-200 sticky top-0 z-10">
                <TableRow>
                  <TableHead className="min-w-[180px] py-3 px-4 text-left text-sm font-semibold text-gray-700">
                    风险名称
                  </TableHead>
                  <TableHead className="w-[200px] py-3 px-4 text-left text-sm font-semibold text-gray-700">
                    一级分类
                  </TableHead>
                  <TableHead className="w-[200px] py-3 px-4 text-left text-sm font-semibold text-gray-700">
                    二级分类
                  </TableHead>
                  <TableHead className="w-[200px] py-3 px-4 text-left text-sm font-semibold text-gray-700">
                    三级分类
                  </TableHead>
                  <TableHead className="min-w-[220px] py-3 px-4 text-left text-sm font-semibold text-gray-700">
                    风险种类
                  </TableHead>
                  <TableHead className="w-[180px] py-3 px-4 text-left text-sm font-semibold text-gray-700">
                    风险等级
                  </TableHead>
                  <TableHead className="min-w-[150px] py-3 px-4 text-left text-sm font-semibold text-gray-700">
                    控制措施
                  </TableHead>
                  <TableHead className="min-w-[150px] py-3 px-4 text-left text-sm font-semibold text-gray-700">
                    适用范围
                  </TableHead>
                  <TableHead className="w-[100px] py-3 px-4 text-right text-sm font-semibold text-gray-700">
                    操作
                  </TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {currentItems.map((risk) => {
                  const riskLevelStyle = getRiskLevelStyle(risk.baseRiskLevel);
                  return (
                    <TableRow
                      key={risk.id}
                      className="transition-colors duration-150 border-b border-gray-100 last:border-0 hover:bg-gray-50"
                    >
                      <TableCell className="py-3 px-4 text-gray-800 text-sm font-medium">
                        {risk.riskName || <span className="text-gray-400">未命名</span>}
                      </TableCell>


                      <TableCell className="py-3 px-4 text-sm">
                        {formatCategory(risk.primaryCategory)}
                      </TableCell>
                      <TableCell className="py-3 px-4 text-sm">
                        {formatCategory(risk.secondaryCategory)}
                      </TableCell>
                      <TableCell className="py-3 px-4 text-sm">
                        {formatCategory(risk.tertiaryCategory)}
                      </TableCell>


                      <TableCell className="py-3 px-4">
                        {formatRiskTypes(risk.riskType)}
                      </TableCell>
                      <TableCell className="py-3 px-4">
                        <Badge className={`${riskLevelStyle.bgColor} px-2 py-0.5 text-xs`}>
                          {risk.baseRiskLevel || "未评级"}
                        </Badge>
                      </TableCell>
                      <TableCell className="py-3 px-4">
                        {formatControlMeasures(risk.controlMeasures)}
                      </TableCell>
                      <TableCell className="py-3 px-4">
                        {formatApplicableScope(risk.applicableScope)}
                      </TableCell>
                      <TableCell className="py-3 px-4 text-right">
                        <DropdownMenu>
                          <DropdownMenuTrigger asChild>
                            <Button
                              variant="ghost"
                              size="icon"
                              className="h-8 w-8 text-gray-600 hover:text-blue-600 hover:bg-blue-50 transition-colors"
                            >
                              <MoreHorizontal className="w-4 h-4" />
                            </Button>
                          </DropdownMenuTrigger>
                          <DropdownMenuContent align="end" className="w-[140px]">
                            <DropdownMenuItem onClick={() => handleEdit(risk)}>
                              <Edit className="w-4 h-4 mr-2" />
                              编辑
                            </DropdownMenuItem>
                            <DropdownMenuSeparator />
                            <DropdownMenuItem
                              onClick={() => onDelete(risk.id)}
                              className="text-red-600"
                            >
                              <Trash2 className="w-4 h-4 mr-2" />
                              删除
                            </DropdownMenuItem>
                          </DropdownMenuContent>
                        </DropdownMenu>
                      </TableCell>
                    </TableRow>
                  );
                })}
              </TableBody>
            </Table>
          </div>
          {renderPagination()}
        </div>
      ) : (
        <div className="text-center py-16 px-4 text-gray-500 border rounded-lg bg-gray-50 border-gray-200">
          <AlertTriangle className="w-10 h-10 mx-auto mb-4 text-gray-300" />
          <h3 className="text-lg font-medium text-gray-600 mb-2">
            暂无匹配的危险点数据
          </h3>
          <p className="text-sm text-gray-400">
            可通过"新建危险点"添加数据，或调整搜索关键词/分类筛选后重试
          </p>
        </div>
      )}
    </div>
  );
}